#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>

#define SERVER_PORT 8888
#define MAX_LISTEN_NUM 10
#define MAX_DATA 1024
#define QUERY_PATTERN "query temperature"

int main()
{
    struct sockaddr_in sourAddr;
    struct sockaddr_in destAddr;
    int sockfd, new_sockfd;
    char buffer[MAX_DATA];
    char temperature[] = "25.5";
    int sinSize = sizeof(destAddr);
    printf("===HY===temperature size = %ld \n", sizeof(temperature));
    
    //create server socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == sockfd)
    {
        printf("create socket error: %d", errno);
        return -1;
    }
    
    //init server IP
    bzero(&sourAddr, sizeof(sourAddr));
    sourAddr.sin_family = AF_INET;
    sourAddr.sin_addr.s_addr = htonl(INADDR_ANY);//set destination IP
    sourAddr.sin_port = htons(SERVER_PORT);  //set destination port
    
	
    //bind socket
    if(0 > bind(sockfd, (struct sockaddr *)&sourAddr, sizeof(sourAddr)))
    {
        printf("bind error: %d", errno);
        return -1;
    }
    
    // start listening
    if(-1 == listen(sockfd, MAX_LISTEN_NUM)) 
    {
    	printf("listen on socket error: %d", errno);
        return -1;
    }
    
    printf("===HY=== \n");
    while(1)
    {
        new_sockfd = accept(sockfd, (struct sockaddr *)&destAddr, &sinSize);
        if(-1 == new_sockfd)
        {
            printf("accept on socket error: %d", errno);
            return -1;
        }
        
        printf("buffer size: %ld \n", sizeof(buffer));
        ssize_t byteRead = recv(new_sockfd, buffer, MAX_DATA, 0);
        if(-1 == byteRead)
        {
            printf("recevice socket data error: %d", errno);
            return -1;
        }
        printf("recevice data: %s \n", buffer);
        buffer[byteRead] = '\0';
        //strncpy(buffer,)
        if(0 == strcmp(buffer, QUERY_PATTERN))
        {
            printf("start send temperature: %s \n", temperature);
            ssize_t byteSend = send(new_sockfd, temperature, strlen(temperature), 0);
            if(-1 == byteSend)
            {
            	printf("send data to socket error: %d", errno);
            	return -1;
            }
        }
            
        //Close socket
        close(new_sockfd);
    }
    close(sockfd);
    return 0;
}

